package com.meviewer.activity.file.browser;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.GridView;
import android.widget.Toolbar;

import com.meviewer.R;
import com.meviewer.activity.BaseActivity;
import com.meviewer.common.Constants;

/**
 * @author ihhr
 */
public class FileBrowserActivity extends BaseActivity {

    public static final String ARG_BOOLEAN_IS_FILE = FileBrowserActivity.class.getName() + ".ARG_IS_FILE";
    public static final String ARG_STRING_ROOT_PATH = FileBrowserActivity.class.getName() + ".ARG_ROOT_PATH";
    public static final String ARG_BOOLEAN_PATH_ALL = FileBrowserActivity.class.getName() + ".ARG_PATH_ALL";
    public static final String ARG_STRING_JS_CONTEXT_FUNCTION_NAME = FileBrowserActivity.class.getName() + ".ARG_JS_CONTEXT_FUNCTION_NAME";


    public static final int ACTION_LOAD_FILE_BROWSER_CODE = Constants.INT32;
    public static final String JS_CONTEXT_FUNCTION_NAME = FileBrowserActivity.class.getName() + ".JS_CONTEXT_FUNCTION_NAME";
    public static final String ARG_FILEPATH = FileBrowserActivity.class.getName() + ".ARG_FILEPATH";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_browser);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_return);
        toolbar.setNavigationOnClickListener(v -> finish());


        boolean isFile = getIntent().getBooleanExtra(ARG_BOOLEAN_IS_FILE, true);
        String rootPath = getIntent().getStringExtra(ARG_STRING_ROOT_PATH);
        boolean pathAll = getIntent().getBooleanExtra(ARG_BOOLEAN_PATH_ALL, true);
        String jsContextFunctionName = getIntent().getStringExtra(ARG_STRING_JS_CONTEXT_FUNCTION_NAME);

        GridView gv = findViewById(R.id.gv);
        FileBrowserGridViewAdapter adapter = new FileBrowserGridViewAdapter(this, findViewById(R.id.tv), isFile, rootPath, pathAll, jsContextFunctionName);
        gv.setAdapter(adapter);

        if (isFile) {
            findViewById(R.id.fab).setVisibility(View.INVISIBLE);
        } else {
            findViewById(R.id.fab).setOnClickListener(v -> {
                Intent back = new Intent();
                back.putExtra(ARG_FILEPATH, adapter.getCatalog());
                back.putExtra(JS_CONTEXT_FUNCTION_NAME, jsContextFunctionName);
                this.setResult(ACTION_LOAD_FILE_BROWSER_CODE, back);
                this.finish();
            });
        }
    }
}